document.addEventListener('DOMContentLoaded', function() {
    console.log('DOM fully loaded and parsed');
    const sendButton = document.getElementById('sendButton');
    const userInput = document.getElementById('userInput');
    const chatMessages = document.getElementById('chatMessages');

    console.log('sendButton:', sendButton);
    console.log('userInput:', userInput);
    console.log('chatMessages:', chatMessages);

    // 在这里填入您的智谱清言API密钥
    const ZHIPUAI_API_KEY = "da443ddc0e5696c24c630fc3ccf6d4a1.oQaR9wTodENBqIIC";

    // 添加初始欢迎消息
    addMessageToChat('ai', '您好！我是筑梦智程的AI助手。有什么我可以帮助您的吗？');

    sendButton.addEventListener('click', function() {
        console.log('Send button clicked');
        handleSendMessage();
    });

    userInput.addEventListener('keypress', function(e) {
        if (e.key === 'Enter') {
            console.log('Enter key pressed');
            handleSendMessage();
        }
    });

    async function handleSendMessage() {
        console.log('handleSendMessage called');
        const userMessage = userInput.value.trim();
        if (userMessage) {
            console.log('User message:', userMessage);
            addMessageToChat('user', userMessage);
            userInput.value = '';
            
            // 添加加载指示器
            const loadingIndicator = addLoadingIndicator();
            
            const aiResponse = await getAIResponse(userMessage);
            console.log('AI response:', aiResponse);
            
            // 移除加载指示器
            loadingIndicator.remove();
            
            addMessageToChat('ai', aiResponse);
        }
    }

    async function getAIResponse(userMessage) {
        try {
            const token = generateJWT(ZHIPUAI_API_KEY);
            const response = await fetch('https://open.bigmodel.cn/api/paas/v4/chat/completions', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${token}`
                },
                body: JSON.stringify({
                    model: "chatglm_turbo",
                    messages: [{ role: "user", content: userMessage }],
                    stream: false,
                    max_tokens: 150
                })
            });

            if (!response.ok) {
                throw new Error(`Network response was not ok: ${response.statusText}`);
            }

            const jsonObj = await response.json();
            console.log('API response:', jsonObj);

            return jsonObj.choices && jsonObj.choices[0].message && jsonObj.choices[0].message.content
                ? jsonObj.choices[0].message.content
                : 'AI did not return a valid response.';
        } catch (error) {
            console.error('Error fetching AI response:', error);
            return '抱歉，我遇到了一些问题。请稍后再试。';
        }
    }

    function generateJWT(apikey) {
        const [id, secret] = apikey.split('.');
        const header = {
            alg: "HS256",
            sign_type: "SIGN"
        };
        const payload = {
            api_key: id,
            exp: Date.now() + 3600 * 1000,
            timestamp: Date.now()
        };
        return KJUR.jws.JWS.sign("HS256", JSON.stringify(header), JSON.stringify(payload), secret);
    }

    function addMessageToChat(sender, message) {
        const messageElement = document.createElement('div');
        messageElement.classList.add('chat-message', sender);
        messageElement.textContent = message;
        chatMessages.appendChild(messageElement);
        chatMessages.scrollTop = chatMessages.scrollHeight;
    }

    function addLoadingIndicator() {
        const loadingElement = document.createElement('div');
        loadingElement.classList.add('chat-message', 'ai', 'loading');
        loadingElement.textContent = 'AI 正在思考...';
        chatMessages.appendChild(loadingElement);
        chatMessages.scrollTop = chatMessages.scrollHeight;
        return loadingElement;
    }
});